//
//  FCLoginViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/22.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

@objc protocol FCLoginDelegate {
    @objc optional func loginView(_ loginView: FCLoginView, didStartLogin data: Any?)
    @objc optional func loginView(_ loginView: FCLoginView, successLogin data: Any?)
    @objc optional func loginView(_ loginView: FCLoginView, loginFailed data: Any?)
}

class FCLoginViewController: UIViewController, FCLoginDelegate, TencentSessionDelegate {
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    var tencentApi: TencentOAuth?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "登陆"
        
        view.backgroundColor = UIColor.white
        
        let bgView = UIImageView(frame: view.frame)
        bgView.image = #imageLiteral(resourceName: "loginBG")
        view.addSubview(bgView)
        
        let loginView = FCLoginView(frame: view.frame)
        loginView.closeBtn.alpha = 0
        loginView.delegate = self
        view.addSubview(loginView)
        
        loginView.qqLoginBtn.addTarget(self, action: #selector(FCLoginViewController.goQQLogin), for: .touchUpInside)
        
        if navigationController == nil{
            let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
            navBar.barStyle = .black
            navBar.tintColor = UIColor.white
            navBar.barTintColor = themeColor2
            
            let navItem = UINavigationItem(title: title!)
            navBar.pushItem(navItem, animated: false)
            navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(FCLoginViewController.closeView))
            
            
            view.addSubview(navBar)
            
            
        }
        
    }

    func loginView(_ loginView: FCLoginView, successLogin data: Any?) {
        closeView()
    }
    
    func loginView(_ loginView: FCLoginView, loginFailed data: Any?) {
        var errMsg = "请求出错"
        
        if data != nil{
            let jsonObj = data as? NSDictionary
            if jsonObj != nil{
                
                errMsg = jsonObj?.object(forKey: "message") as? String ?? "请求出错"
            }
        }
        let alert = UIAlertController(title: errMsg, message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    func goQQLogin(){
        if tencentApi == nil{
            tencentApi = TencentOAuth(appId: "101382009", andDelegate: self)
        }
        let permission:[Any] = [
            kOPEN_PERMISSION_GET_USER_INFO,
            kOPEN_PERMISSION_GET_SIMPLE_USER_INFO
        ]
        //        NSArray(objects: "get_user_info",) as [Any]
        tencentApi?.authorize(permission, inSafari: false)
        //        tencentApi?.authorize(permission)
        
        //        let mahuateng = (UIApplication.shared.delegate as? AppDelegate)?.tencentApi
        //        mahuateng?.goLogin()
        
        //        sdkCall.getinstance().oauth.authorize(permission)
        
    }
    
    public func tencentDidLogin() {
        print("tencentDidLogin: \(tencentApi?.accessToken ?? "openid nil")")
        
        var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=login&a=qqGetOpenId")!)
        resq.httpMethod = "POST"
        resq.httpBody = "access_token=\(tencentApi?.accessToken ?? "")".data(using: .utf8)
        
        URLSession.shared.dataTask(with: resq) { (data, _, err) in
            do{
                if err != nil{
                    throw err!
                }
                
                let unionID = String(data: data!, encoding: .utf8)
                
                print("miaoyin_union_openid: \(unionID ?? "data nil")")
                
                if unionID != nil {
                    var loginReq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=login&a=appQQLogin")!)
                    loginReq.httpMethod = "POST"
                    loginReq.httpBody = "openid=\(unionID!)".data(using: .utf8)
                    URLSession.shared.dataTask(with: loginReq, completionHandler: { (dataa, _, errr) in
                        do{
                            if errr != nil{
                                throw errr!
                            }
                            
                            print(String(data: dataa!, encoding: .utf8) ?? "dataa nil")
                            
                            let jsonObj = try JSONSerialization.jsonObject(with: dataa!, options: .allowFragments) as? NSDictionary
                            let reCode = jsonObj?.object(forKey: "code") as? Int
                            
                            if reCode == 200{
                                
                                let cookies = HTTPCookieStorage.shared.cookies!
                                let cookiesData = NSKeyedArchiver.archivedData(withRootObject: cookies)
                                UserDefaults.standard.set(cookiesData, forKey: cookieKey)
                                UserDefaults.standard.set(unionID!, forKey: loginUserDefaultKeyName)
                                
                                DispatchQueue.main.async {
                                    self.dismiss(animated: true, completion: nil)
                                    let app = UIApplication.shared.delegate as? AppDelegate
                                    if app != nil{
//                                        app!.tabController.presentedViewController?.dismiss(animated: true, completion: nil)
                                        app!.tabController.fileView?.alpha = 0
                                        
                                        if app!.wodeVCLoaded {
                                            app!.wodeVC.loadUserData()
                                        }
                                    }
                                    
                                }
                                
                                URLSession.shared.dataTask(with: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo")!) { (data:Data?, resp:URLResponse?, err:Error?) in
                                    do{
                                        if err != nil{
                                            throw err!
                                        }
                                        
                                        print(String(data: data!, encoding: .utf8) ?? "data nil")
                                        
                                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                                        let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                                        
                                        let nickName = jsonData?.object(forKey: "nickname") as? String
                                        let face = jsonData?.object(forKey: "face") as? String
                                        
                                        if !ChangyanSDK.isLogin(){
                                            ChangyanSDK.loginSSO(unionID!, userName: nickName ?? "", profileUrl: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo", imgUrl: face ?? "", complete: { (code, msg) in
                                                if code == CYSuccess {
                                                    print("changyan login success:")
                                                    print(msg ?? "no respond")
                                                }
                                            })
                                        }
                                        
                                    }catch let ex{
                                        print(ex)
                                    }
                                    }.resume()
                                
                                
                            }else if reCode == 201 {
                                DispatchQueue.main.async {
                                    self.dismiss(animated: true, completion: nil)
                                    let app = UIApplication.shared.delegate as? AppDelegate
                                    if app != nil{
                                        app!.tabController.selectedIndex = 2
//                                        app!.tabController.presentedViewController?.dismiss(animated: true, completion: nil)
                                        app!.tabController.bgView.alpha = 0
                                        app!.tabController.fileView?.alpha = 0
                                        app!.wodeVC.gotoBindVC(type: .weixin, code: nil, openid: unionID)
                                    }
                                    
                                }
                            }else{
                                let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                                DispatchQueue.main.async {
                                    self.present(alert, animated: true, completion: nil)
                                }
                            }
                            
                            
                        }catch let exx{
                            let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                            DispatchQueue.main.async {
                                self.present(alert, animated: true, completion: nil)
                            }
                            print(exx)
                        }
                    }).resume()
                }
            }catch let ex{
                let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }
                print(ex)
            }
            }.resume()
    }
    
    
    public func tencentDidNotLogin(_ cancelled: Bool) {
        
    }
    
    
    func tencentDidNotNetWork() {
        
    }
    
    func closeView(){
        dismiss(animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

class FCLoginView: UIView{
    
    var delegate: FCLoginDelegate?
    
    var scrollView: UIScrollView!
    
    var closeBtn : UIButton!
    
    var userNameInput: FCLoginInput!
    var passwordInput: FCLoginInput!
    
    var regBtn: UIButton!
    var forgetBtn: UIButton!
    
    var loginBtn: UIButton!
    
    var loadingView: LLFullScreenLoading!
    
    var qqLoginBtn: UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
//        let bgView = UIImageView(frame: frame)
//        bgView.image = #imageLiteral(resourceName: "loginBG")
//        addSubview(bgView)
        
        let scrollView = UIScrollView(frame: frame)
        scrollView.alwaysBounceVertical = true
        scrollView.keyboardDismissMode = .onDrag
        scrollView.backgroundColor = UIColor.clear
        addSubview(scrollView)
        
        let cardView = UIView(frame: CGRect(x: 0, y: 0, width: frame.width - 64, height: 350))
        cardView.center = center
        cardView.backgroundColor = UIColor.white
        cardView.layer.cornerRadius = 8
        scrollView.addSubview(cardView)
        
        closeBtn = UIButton(frame: CGRect(x: cardView.frame.width - 20, y: 4, width: 16, height: 16))
//        closeBtn.backgroundColor = UIColor.red
        closeBtn.setTitle("×", for: .normal)
        closeBtn.setTitleColor(UIColor.lightGray, for: .normal)
        closeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        cardView.addSubview(closeBtn)
        
        let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: cardView.frame.width - 32, height: 44.0*6.0))
        stackView.center = CGPoint(x: cardView.frame.width/2, y: cardView.frame.height/2)
        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.spacing = 8
        cardView.addSubview(stackView)
        
        
        //1
        userNameInput = FCLoginInput(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: 44), type: .phone)
        userNameInput.maxLength = 11
        userNameInput.input.returnKeyType = .next
        userNameInput.input.addTarget(self, action: #selector(FCLoginView.nextPassword), for: .editingDidEndOnExit)
        stackView.addArrangedSubview(userNameInput)
        
        
        
        //2
        passwordInput = FCLoginInput(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: 44), type: .password)
        passwordInput.maxLength = 20
        stackView.addArrangedSubview(passwordInput)
        passwordInput.input.addTarget(self, action: #selector(FCLoginView.goLogin), for: .editingDidEndOnExit)
        
        
        //3
        let btnRow = UIView(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: 44))
        stackView.addArrangedSubview(btnRow)
        
        regBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 72, height: 44))
        regBtn.setTitle("立即注册", for: .normal)
        regBtn.setTitleColor(UIColor.lightGray, for: .normal)
        regBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btnRow.addSubview(regBtn)
        
        forgetBtn = UIButton(frame: CGRect(x: btnRow.frame.width - 72, y: 0, width: 72, height: 44))
        forgetBtn.setTitle("忘记密码", for: .normal)
        forgetBtn.setTitleColor(UIColor.lightGray, for: .normal)
        forgetBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btnRow.addSubview(forgetBtn)
        
        //4
        loginBtn = UIButton(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: 44))
        loginBtn.setTitle("登陆", for: .normal)
        loginBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        loginBtn.backgroundColor = themeColor1
        loginBtn.layer.cornerRadius = 4
        stackView.addArrangedSubview(loginBtn)
        loginBtn.addTarget(self, action: #selector(FCLoginView.goLogin), for: .touchUpInside)
        
        //4
        let seperatorView = UILabel(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: 44))
        stackView.addArrangedSubview(seperatorView)
        
        let seperatorLine = UIView(frame: CGRect(x: 0, y: 22, width: stackView.frame.width, height: 1))
        seperatorLine.backgroundColor = UIColor.lightGray
        seperatorView.addSubview(seperatorLine)
        
        let seperatorTitle = UILabel(frame: CGRect(x: 0, y: 0, width: 120, height: 44))
        seperatorTitle.center.x = stackView.frame.width/2
        seperatorTitle.backgroundColor = UIColor.white
        seperatorTitle.text = "用其他方式登录"
        seperatorTitle.textColor = UIColor.lightGray
        seperatorTitle.font = UIFont.systemFont(ofSize: 14)
        seperatorTitle.textAlignment = .center
        seperatorView.addSubview(seperatorTitle)
        
        
        //5
        let btnRow2 = UIView(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: 44))
        stackView.addArrangedSubview(btnRow2)
        
        qqLoginBtn = UIButton(frame: CGRect(x: 0, y: 4, width: 36, height: 36))
        qqLoginBtn.center.x = stackView.frame.width/2 - 44
        qqLoginBtn.setImage(#imageLiteral(resourceName: "qq_icon"), for: .normal)
        qqLoginBtn.imageView?.contentMode = .scaleAspectFit
        btnRow2.addSubview(qqLoginBtn)
        
        if !UIApplication.shared.canOpenURL(URL(string: "mqq://")!){
            qqLoginBtn.alpha = 0
        }
        
        let wxLoginBtn = UIButton(frame: CGRect(x: 0, y: 4, width: 36, height: 36))
        wxLoginBtn.center.x = stackView.frame.width/2 + 44
        wxLoginBtn.setImage(#imageLiteral(resourceName: "wechat"), for: .normal)
        wxLoginBtn.imageView?.contentMode = .scaleAspectFit
        btnRow2.addSubview(wxLoginBtn)
        wxLoginBtn.addTarget(self, action: #selector(FCLoginView.goWXLogin), for: .touchUpInside)
        
        if !WXApi.isWXAppInstalled(){
            wxLoginBtn.alpha = 0
        }
        
        loadingView = LLFullScreenLoading(frame: frame)
        loadingView.alpha = 0
        addSubview(loadingView)
    }
    
    func nextPassword(){
        passwordInput.input.becomeFirstResponder()
    }
    
    func goLogin(){
        
        userNameInput.input.resignFirstResponder()
        passwordInput.input.resignFirstResponder()
        if checkInput(){
            postRequet()
        }
    }
    
    func checkInput() -> Bool{
        if userNameInput.input.text == "" {
            userNameInput.input.becomeFirstResponder()
            return false
        }
        
        if passwordInput.input.text == "" {
            passwordInput.input.becomeFirstResponder()
            return false
        }
        
        
        return true
    }
    
    func postRequet(){
        delegate?.loginView?(self, didStartLogin: "username=\(userNameInput.input.text!)&password=\(passwordInput.input.text!)")
        loadingView.alpha = 1
        let urlStr = "\(apiBaseDomainName)?m=admin&c=login&a=userLogin"
        print(urlStr)
        var resq = URLRequest(url: URL(string: urlStr)!)
        resq.httpMethod = "POST"
//        print("username=\(userNameInput.input.text!)&password=\(passwordInput.input.text!)")
        resq.httpBody = "username=\(userNameInput.input.text!)&password=\(passwordInput.input.text!)".data(using: .utf8)
        URLSession.shared.dataTask(with: resq) { (data:Data?, resp:URLResponse?, err:Error?) in
            DispatchQueue.main.async {
                self.loadingView.alpha = 0
            }
            do{
                if err != nil{
                    throw err!
                }
                if data == nil{
                    throw NSError(domain: "network_err", code: 9, userInfo: nil)
                }
                print(String(data: data!, encoding: .utf8) ?? "data not utf8")
                
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let code = jsonObj?.object(forKey: "code") as? Int
                if code == 200{
                    let cookies = HTTPCookieStorage.shared.cookies!
                    let cookiesData = NSKeyedArchiver.archivedData(withRootObject: cookies)
                    UserDefaults.standard.set(cookiesData, forKey: cookieKey)
                    
                    UserDefaults.standard.set(self.userNameInput.input.text!, forKey: loginUserDefaultKeyName)
                    
                    
                    URLSession.shared.dataTask(with: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo")!) { (data:Data?, resp:URLResponse?, err:Error?) in
                        do{
                            if err != nil{
                                throw err!
                            }
                            
                            print(String(data: data!, encoding: .utf8) ?? "data nil")
                            
                            let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                            let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                            
                            let nickName = jsonData?.object(forKey: "nickname") as? String
                            let face = jsonData?.object(forKey: "face") as? String
                            
                            if !ChangyanSDK.isLogin(){
                                ChangyanSDK.loginSSO(self.userNameInput.input.text!, userName: nickName ?? "", profileUrl: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo", imgUrl: face ?? "", complete: { (code, msg) in
                                    if code == CYSuccess {
                                        print("changyan login success:")
                                        print(msg ?? "no respond")
                                    }
                                })
                            }
                            
                        }catch let ex{
                            print(ex)
                        }
                    }.resume()
                    
                    
                    
                    DispatchQueue.main.async {
                        self.delegate?.loginView?(self, successLogin: jsonObj)
                    }
                }else{
                    DispatchQueue.main.async {
                        self.delegate?.loginView?(self, loginFailed: jsonObj)
                    }
                }
                
                
            }catch let ex{
                print(ex)
                DispatchQueue.main.async {
                    self.delegate?.loginView?(self, loginFailed: ex)
                }
            }
        }.resume()
    }
    
    func goWXLogin(){
        print("wxlogin")
        
        if WXApi.isWXAppInstalled(){
            let req = SendAuthReq()
            req.scope = "snsapi_userinfo"
            WXApi.send(req)
        }
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

